package com.project.practice11_24.aspect;

import com.project.practice11_24.mapper.IManMapper;
import com.project.practice11_24.mapper.IStudentMapper;
import com.project.practice11_24.service.IStudentService;
import com.project.practice11_24.service.impl.BaseService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Field;

@Component
@Aspect
public class StudentAspect {
    private static SqlSessionFactory factory;

    static {
        try {
            Reader r = Resources.getResourceAsReader("mybatis.cfg.xml");
            factory = new SqlSessionFactoryBuilder().build(r);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //申明目标对象的范围，第一个*号表示返回类型为任意返回类型
    //om.project.service. *.*  表示om.project.service包中所有的类中，所有的方法
    //(..)表示方法参数为任意类型
    //..*.*是包含此包的子包
    @Around("execution(* com.project.practice11_24.service.impl..*.*(..))")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {

        SqlSession session=factory.openSession();
        //得到目标对象
        Object obj = joinPoint.getTarget();
        //得到目标对象的属性集合
        Field[] array = obj.getClass().getDeclaredFields();
        for(Field f : array){
            //判断属性是不是接口，并且以Mapper名字结尾的
            if(f.getType().isInterface() && f.getType().getName().endsWith("Mapper")){
                //得到mapper对象
              Object mapperObj =  session.getMapper(f.getType());
              f.setAccessible(true);
              //设置此属性的值
              f.set(obj,mapperObj);
            }
        }

        //执行目标方法,得到目标方法执行后的返回值
        Object retrunObject =  joinPoint.proceed();

        session.commit();
        session.close();
        return retrunObject;
    }
}
